/*
 * Usage: ./tee [-a] file
 */

#include "command.h"
#include "raw_mode.h"

int _tee(char *argv[])
{
	/* check the number of cmd-line parameters is correct */
	int argc = 0;
	for (char **ptr = argv; *ptr != NULL; ptr++)
		argc++;

	if (argc > 3 || argc == 1) {
		fprintf(stderr, "Usage: tee [-a] file\n");
		return -1;
	}

	int open_flags = O_CREAT | O_WRONLY | O_TRUNC; /* default open falgs */
	mode_t file_perms = 0644; 	/* rw-r--r-- */

	int opt; 	/* option character */
	const char *opt_fmt = "a"; 	/* option format */
	
	/* parse the cmd-line parameters */
	while ((opt = getopt(argc, argv, opt_fmt)) != -1) {
		switch (opt) {
			case 'a':
				open_flags = O_CREAT | O_WRONLY | O_APPEND;
				break;
			default:
				fprintf(stderr, "Usage: tee [-a] file\n");
				return -1;
		}
	}

	/* open the file */
	const char *filename = argv[optind];
	int fd = open(filename, open_flags, file_perms);
	if (fd == -1) {
		fprintf(stderr, "tee error: open\n");
		return -1;
	}

	/* read from stdin and write to stdout and given file */
	int num_read;
	int num_written;
	char buf[BUF_SIZE];

	while ((num_read = read(STDIN_FILENO, buf, BUF_SIZE)) != -1) {
		/* write to stdout */
		num_written = write(STDOUT_FILENO, buf, num_read);
		if (num_written != num_read) {
			fprintf(stderr, "tee error: write to stdout\n");
			return -1;
		}
		/* write to given file */
		num_written = write(fd, buf, num_read);
		if (num_written != num_read) {
			fprintf(stderr, "tee error: write to file\n");
			return -1;
		}
	}

	/* close the file */
	if (close(fd) == -1) {
		fprintf(stderr, "tee error: close\n");
		return -1;
	}
	return 0;
}
